App({
  onLaunch: function () {
    wx.getUserInfo({
      success: res => {
        this.globalData.userInfo = res.userInfo
        this.globalData.nickName = res.userInfo.nickName
        this.globalData.avatarUrl = res.userInfo.avatarUrl
        if (this.userInfoReadyCallback) {
          this.userInfoReadyCallback(res)
        }
      },
      fail: res => {
        var that = this;
        wx.showModal({
          title: '微信授权',
          content: '若不授权微信登录，而无法获取用户头像及姓名。点击重新授权，则可重新使用；若点击不授权，需要在微信【发现】-【小程序】中删掉小程序，重新搜索授权登录，才可使用',
          cancelText: '不授权',
          confirmText: '授权',
          success: function (res) {
            if (res.confirm) {
              wx.openSetting({
                success: (res) => {
                  if (res.authSetting["scope.userInfo"]) {
                    wx.getUserInfo({
                      success: function (res) {
                        that.globalData.userInfo = res.userInfo,
                        that.globalData.nickName = res.userInfo.nickName,
                        that.globalData.avatarUrl = res.userInfo.avatarUrl
                      }
                    })
                  }
                }
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    })

    // 登录
    wx.login({
      success: res => {
        var that = this;
        wx.request({
          url: 'https://cake.cindata.cn/contact/getOpenId',
          data: {
            code: res.code,
            fullName: this.globalData.nickName,
            avatarUrl: this.globalData.avatarUrl
          },
          method: 'POST',
          header: {
            'content-type': 'application/json'
          },
          success: function success(res) {
            that.globalData.openId = res.data.openId
          }
        });
      }
    })
  },
  // ========== 应用程序全局方法 ==========
  fetchApi(url, callback) {
    wx.request({
      url,
      data: {
        openId: this.globalData.openId
      },
      method: 'POST',
      header: {
        'Content-type': 'application/json'
      },
      success(res) {
        callback(null, res.data)
      },
      fail(e) {
        callback(e)
      }
    })
  },
  // ========== 应用程序全局方法 ==========
  fetchApiById(url, id, callback) {
    wx.request({
      url,
      data: {
        openId: this.globalData.openId,
        id: id
      },
      method: 'POST',
      header: {
        'Content-type': 'application/json'
      },
      success(res) {
        callback(null, res.data)
      },
      fail(e) {
        callback(e)
      }
    })
  },
  globalData: {
    userInfo: null,
    nickName: '',
    avatarUrl:'',
    openId: null
  }
})